package com.fsnbigdata.handle;


import com.fsnbigdata.domain.Log;
import com.fsnbigdata.exception.ParamException;
import com.fsnbigdata.security.auth.TokenHelper;
import com.fsnbigdata.service.api.LogService;
import com.fsnbigdata.util.IPTOAddress;
import com.fsnbigdata.vo.ResultVO;
import com.fsnbigdata.vo.ResultVOUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Description 全局异常处理
 * @Author
 * @Date 2018/12/15 16:56
 **/
@ControllerAdvice
public class ParamExceptionHandle {

     @Autowired
     private TokenHelper tokenHelper;

     @Autowired
     private LogService logService;

     @ExceptionHandler(value = ParamException.class)
     @ResponseBody
     public ResultVO handlerSellerException(ParamException e){
         return ResultVOUtil.error(e.getCode(),e.getMessage());
     }

    @ResponseBody
    @ExceptionHandler(value = RuntimeException.class)
    public void exceptionHandler(RuntimeException e,  HttpServletRequest httpServletRequest) throws Exception {

        String authToken = tokenHelper.getToken(httpServletRequest);
        String username = tokenHelper.getUsernameFromToken(authToken);
        if (authToken!=null&&username!=null){
            Log log = new Log();
            log.setDescription(e.toString());
            //类型  异常记录类型
            log.setGenre("1");
            log.setAddress(IPTOAddress.addr(IPTOAddress.getIP(httpServletRequest)));
            log.setClientInformation(IPTOAddress.getAddr(httpServletRequest));
            log.setIp(IPTOAddress.getIP(httpServletRequest));
            log.setUsername(username);
            log.setCreateTime(new Date());
            log.setType("exception");
            //保存日志
            logService.save(log);

        }
    }
}
